package com.share.two.aio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.Future;

/**
 * 坑1：不能多个客户端用一个channel：实例化一个channel(channel.open()&&channel.connect()),实例化多个client。
 *     这多个client共用一个实例化的channel。
 *   改正：不用的client要用不同的channel：---->有几个client，channel就要open几回
 *   
 * 坑2：channel.read(buffer)  、   channel.write(buffer)  之后，要想获取buffer的信息就要buffer.flip()
 * 
 * 
 *
 */
public class Client{

	//	private AsynchronousSocketChannel asc;
	//
	//	public AsynchronousSocketChannel getAsc() {
	//		return asc;
	//	}
	//
	//	public void setAsc(AsynchronousSocketChannel asc) {
	//		this.asc = asc;
	//	}
	//	
	//	
	//	
	//	public Client(AsynchronousSocketChannel asc) {
	//		super();
	//		this.asc = asc;
	//	}

	private AsynchronousSocketChannel asc ;

	public Client() throws Exception {
		asc = AsynchronousSocketChannel.open();
	}

	public void connect(){
		asc.connect(new InetSocketAddress("127.0.0.1", 12345));
	}

	public void write(String string){
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		buffer.put(string.getBytes());
		buffer.flip();
		try {
			//Future<Integer> write = asc.write(buffer);---->future设计模式，异步的方式
			asc.write(buffer).get();
			System.out.println("client:  发送" + string);
			read();
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}

	public void read(){
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		try {
			//<Integer> read = asc.read(buffer);---->future设计模式，异步的方式
			asc.read(buffer).get();
			buffer.flip();
			System.out.println("client: 接收" + new String(buffer.array(), 0, buffer.remaining()));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws Exception {
//		AsynchronousSocketChannel asc = AsynchronousSocketChannel.open();
//		asc.connect(new InetSocketAddress("127.0.0.1", 12345));
		
//		Client c1 = new Client(asc);
//		Client c2 = new Client(asc);
//		Client c3 = new Client(asc);

		Client c1 = new Client();
		Client c2 = new Client();
		Client c3 = new Client();
		
		c1.connect();
		c2.connect();
		c3.connect();

		c1.write("c1111");
		c2.write("c2222");
		c3.write("c3333");

	}



}
